import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_mwm/base/base.dart';
import 'package:flutter_mwm/beans/bean.dart';
import 'package:flutter_mwm/util/util.dart';
import 'package:flutter_mwm/widget/text.dart';
import 'package:flutter_mwm/widget/widget.dart';
import 'package:qr_flutter/qr_flutter.dart';

class QrCodeHome extends BaseWidget<QrCodeHome> {
  final String username;

  const QrCodeHome({this.username});

  @override
  State<StatefulWidget> createState() {
    return _StateQrCode();
  }
}

class _StateQrCode extends StateBase<QrCodeHome> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('我的二维码'),
        backgroundColor: Color(0xFF051728),
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.more_horiz, color: Colors.white),
              onPressed: _action),
        ],
      ),
      body: Center(
        child: ClickLayout(child: _qrView(), onLongPress: _action),
      ),
    );
  }

  //-----------View-------------

  QrImage qrView;

  /*二维码*/
  Widget _qrView() {
    return QrImage(
      data: 'test',
      size: 256.0,
      errorStateBuilder: (context, error) {
        return Text(error);
      },
    );
  }

  Widget _line() {
    return Line(
      color: Colors.grey[300],
      height: 1,
    );
  }

  Widget _bottomItemMenu(String menuText, {GestureTapCallback itemCallback}) {
    return ListTile(
      dense: true,
      title: TextView(
        menuText,
        //style: TextStyle(fontSize: 18.0, color: Colors.black),
      ),
      onTap: itemCallback,
    );
  }

  //---------method---------

  void _action() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              _bottomItemMenu('保存到手机', itemCallback: (() {
                Navigator.pop(context);
                _saveQrImage();
              })),
              _line(),
              _bottomItemMenu('扫一扫', itemCallback: (() {
                Navigator.pop(context);
                _start2Scan();
              })),
              _line(),
              _bottomItemMenu("分享", itemCallback: () {
                Navigator.pop(context);
                ToastUtil.show(context, '暂未实现，请耐心等候！');
              })
            ],
          );
        });
  }

  /*保存二维码*/
  void _saveQrImage() async {
    ByteData byteData = await QrPainter(
            data: "test",
            gapless: true,
            emptyColor: Colors.white,
            version: QrVersions.auto)
        .toImageData(256);
    var uint8List = byteData.buffer.asUint8List();

    String username = widget.username;
    try {
      File file =
          await FileUtil.writeAsBytes('images/qr_$username.png', uint8List);
      Log.out(file.path);
      showToast('二维码图片保存${await file.exists() ? '成功' : '失败'}');
    } catch (e) {
      showToast('保存二维码图片失败:' + e.toString());
    }
  }

  void _start2Scan() {
    Navigator.pop(context);
    _start2Qr().then((ReturnBean resultBean) {
      String code = null == resultBean ? '' : resultBean.code;
      String message = null == resultBean ? '' : resultBean.message;
      if (!TextUtils.equals('1', code)) {
        showPromptDialog(TextUtils.isEmpty(message) ? "解析失败，请重新扫描！" : message);
        return;
      }
      showToast('$message');
    });
  }
}

/*扫一扫*/
Future<ReturnBean> _start2Qr() async {
  Map<String, dynamic> map = {};
  /*这块不能用{'code':'',message:''},如果用的话，下面需要用
      map.update("code", (dynamic value){
       value="";
     });
     map.update("message", (dynamic value){
       value="";
     });
     */

  return ReturnBean.fromJson(map);
}
